import { ConditionUnit, getWherePartFromConditionUnits, SqlDataType } from "./SqlUtil";
import { relationalStore } from "@kit.ArkData";
import { PageInfo } from "@kit.ArkUI";
import { AppOrderDesc, AppOrderInfo, AppPageInfo, } from "./SqlBaseData";

export enum SelectFun {
  Count = "Count"
}

export interface AppSelectOptions {
  tableName: string,
  selectKeys?: string[] | string | SelectFun,
  conditions?: ConditionUnit[],
  pageInfo?: AppPageInfo,
  orderInfo?: AppOrderInfo
}

export function generateSelectSqlAndArgs(o: AppSelectOptions): [string, SqlDataType[]] {
  let selectPart: string = "*";
  if (o.selectKeys) {
    if (typeof o.selectKeys === 'string') {
      if (o.selectKeys === SelectFun.Count) {
        selectPart = "COUNT (*)"
      } else {
        selectPart = o.selectKeys;
      }
    } else {
      if (o.selectKeys instanceof Array) {
        selectPart = o.selectKeys.join(",");
      }
    }
  }
  const [wherePart, whereValues] = getWherePartFromConditionUnits(o.conditions);
  let sql: string = `SELECT ${selectPart} FROM ${o.tableName} ${wherePart}`;
  if (o.pageInfo) {
    const pageInfoStr = ` LIMIT ${o.pageInfo.offset},${o.pageInfo.pageSize} `
    sql += pageInfoStr
  }
  if (o.orderInfo) {
    const orderInfo = ` ORDER BY ${o.orderInfo.by} ${o.orderInfo.desc ? AppOrderDesc.Desc : AppOrderDesc.Asc} `
    sql += orderInfo;
  }
  return [sql, whereValues];
}

/**
 * 读取当前行指定列的数据
 * @param cursor
 * @param types
 * @param columnIndex
 * @returns
 */
export function getCursorValue(cursor: relationalStore.ResultSet, types: string, columnIndex: number) {
  switch (types) {
    case 'TEXT':
      return cursor.getString(columnIndex);
    case 'INTEGER':
      return cursor.getLong(columnIndex);
    case 'REAL':
      return cursor.getDouble(columnIndex);
    case 'BLOB':
      return cursor.getBlob(columnIndex);
  }
}